﻿using System;
using System.Linq;

namespace IndentationSplitter
{
    internal class IndentationFormat
    {
        private readonly string[] _lines;

        public IndentationFormat(string text)
        {
            _lines = text.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
            if (HasTabIndentation)
            {
                IndentationString = "\t";
                TabbedText = text;
            }
            else
            {
                IndentationString = FindSpaceIndentation();
                TabbedText = text.Replace(IndentationString, "\t");
            }            
        }

        public string IndentationString { get; private set; }

        private string FindSpaceIndentation()
        {
            var firstIndentedRow = _lines.First(l => l.StartsWith(" "));
            return GetLeadingSpaces(firstIndentedRow);    
        }

        private string GetLeadingSpaces(string text)
        {
            return new string(text.TakeWhile(c => c == ' ').ToArray());
        }

        protected bool HasTabIndentation
        {
            get { return _lines.Any(l => l.StartsWith("\t")) || _lines.Any(l => l.StartsWith(" ")) == false; }
        }

        public string TabbedText { get; set; }
    }
}